/* -------------------------------------------------------------------------- */
/*                              passport 验证用户名密码
/* -------------------------------------------------------------------------- */

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const crypto = require('crypto');
const { getUser } = require('../service/user');

passport.use(new LocalStrategy({
  // 默认从 req.body 中取
  usernameField: 'username',
  passwordField: 'password',
},
  async function (username, password, done) {
    try {
      const row = await getUser({ username });
      if (!row) {
        return done(null, false, { message: '用户名或者密码错误' });
      }

      // ⚠️ 重要：将数据库中的十六进制字符串转换回 Buffer
      const saltBuffer = Buffer.from(row.salt, 'hex');
      const storedPasswordBuffer = Buffer.from(row.password, 'hex');

      // 使用同步方法加密用户输入的密码（返回 Buffer）
      const hashedPasswordBuffer = crypto.pbkdf2Sync(password, saltBuffer, 310000, 32, 'sha256');

      // 使用时间安全的比较方法（防止时序攻击）
      if (!crypto.timingSafeEqual(hashedPasswordBuffer, storedPasswordBuffer)) {
        return done(null, false, { message: '用户名或者密码错误' });
      }

      return done(null, row);
    } catch (error) {
      console.error('Passport authentication error:', error);
      return done(error);
    }
  }
));

passport.serializeUser(function (user, cb) {
  process.nextTick(function () {
    cb(null, { id: user.id, username: user.username });
  });
});

passport.deserializeUser(function (user, cb) {
  console.log("deserializeUser", user);
  process.nextTick(function () {
    return cb(null, user);
  });
});


module.exports = passport;
